﻿using AutoMapper;
using B.S.Data.MES.API.Dto.DTOProcess;
using B.S.Data.MES.API.Dto.GenerateIDto;
using B.S.Domain.Generateplan;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.EntityFrameworkCore;

namespace B.S.Data.MES.API.Applications.GenerateItemsApplication
{
    /// <summary>
    /// 分页显示生产计划物品处理器
    /// </summary>
    public class ShowGenerateItemsCommandHorter : IRequestHandler<ShowGenerateItemsCommand, APIPageing<List<DtoGenerateItems>>>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<GenerateItems> _repository;

        public ShowGenerateItemsCommandHorter(IMapper mapper, IBaseRepository<GenerateItems> repository)
        {
            _mapper = mapper;
            _repository = repository;
        }

        public async Task<APIPageing<List<DtoGenerateItems>>> Handle(ShowGenerateItemsCommand request, CancellationToken cancellationToken)
        {
            var res = new APIPageing<List<DtoGenerateItems>>();

            // 构建查询条件
            var query = _repository.GetAll().Where(o => o.IsDel == false);

            // 添加搜索条件
            if (!string.IsNullOrEmpty(request.ItemNumber))
            {
                query = query.Where(x => x.ItemNumber.Contains(request.ItemNumber));
            }

            if (!string.IsNullOrEmpty(request.ItemName))
            {
                query = query.Where(x => x.ItemName.Contains(request.ItemName));
            }

            if (!string.IsNullOrEmpty(request.ItemCategory))
            {
                query = query.Where(x => x.ItemCategory == request.ItemCategory);
            }

            if (request.GenerateplanBasicId.HasValue)
            {
                query = query.Where(x => x.GenerateplanBasicId == request.GenerateplanBasicId.Value);
            }

            // 异步获取总记录数
            res.TotalCount = await query.CountAsync(cancellationToken);
            res.Total = (int)Math.Ceiling(res.TotalCount * 1.0 / request.PageSize);

            // 异步执行分页查询
            var pagelist = await query.OrderByDescending(o => o.GenerateItemsId)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize).ToListAsync(cancellationToken);

            var sou = _mapper.Map<List<DtoGenerateItems>>(pagelist);
            res.Data = sou;
            
            return res;
        }
    }

    /// <summary>
    /// 根据ID获取单个生产计划物品处理器
    /// </summary>
    public class GetGenerateItemByIdCommandHandler : IRequestHandler<GetGenerateItemByIdCommand, APIRequst<DtoGenerateItems>>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<GenerateItems> _repository;

        public GetGenerateItemByIdCommandHandler(IMapper mapper, IBaseRepository<GenerateItems> repository)
        {
            _mapper = mapper;
            _repository = repository;
        }

        public async Task<APIRequst<DtoGenerateItems>> Handle(GetGenerateItemByIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var generateItem = await _repository.GetAll()
                    .Where(x => x.GenerateItemsId == request.GenerateItemsId && x.IsDel == false)
                    .FirstOrDefaultAsync(cancellationToken);

                if (generateItem == null)
                {
                    return new APIRequst<DtoGenerateItems>
                    {
                        Code = RequstCode.失败,
                        Msg = "物品不存在",
                        Data = null!
                    };
                }

                var dto = _mapper.Map<DtoGenerateItems>(generateItem);

                return new APIRequst<DtoGenerateItems>
                {
                    Code = RequstCode.成功,
                    Msg = "获取成功",
                    Data = dto
                };
            }
            catch (Exception ex)
            {
                return new APIRequst<DtoGenerateItems>
                {
                    Code = RequstCode.失败,
                    Msg = $"获取失败：{ex.Message}",
                    Data = null!
                };
            }
        }
    }
}
